import Vue from 'vue'

let messageInstance = null

const createInstance = (text) => {
  const instance = new Vue({
    data() {
      return {
        visible: false
      }
    },
    render(h) {
      // let contentNode = [
      //   h('div', { attrs: { class: 'k-message-mask' } }),
      //   h('div', { attrs: { class: 'k-message-inner' } },
      //     [
      //       text ? h('span', { attrs: { class: 'k-message-text' } }, text) : null
      //     ])
      // ]
      // return h('div', { attrs: { class: 'k-message' } }, [contentNode]);
      return (
        <div class="k-message">
          <div class="k-message-mask"></div>
          <transition name="k-message-slide">
            <div class="k-message-inner" v-show={this.visible}>{text}</div>
          </transition>
        </div>
      )
    },
    methods: {
      show() {
        this.visible = true
        this.timer = setTimeout(() => {
          this.visible = false
          setTimeout(() => {
            this.destroy()
          }, 300);
        }, 3500);
      },
      destroy() {
        clearTimeout(this.timer)
        document.body.removeChild(this.$el)
        messageInstance = null
      }
    }
  })
  const component = instance.$mount()
  document.body.appendChild(component.$el)
  return {
    show() {
      component.show()
    },
    destroy() {
      component.destroy()
    }
  }
}

let getMessage = (text) => {
  messageInstance && messageInstance.destroy()
  messageInstance = createInstance(text)
  return messageInstance.show()
}
let Message = {}
Message.show = (text) => {
  return getMessage(text)
}
Message.hide = e => {
  if (messageInstance) messageInstance.destroy()
}

export default Message